package com.campfire.intelligentsecurity.sys.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@ServerEndpoint("/ws/wzMsgPushServ/{taskid}")
public class WzMsgPushServer extends BaseService {
    private static Logger LOG = LoggerFactory.getLogger(WzMsgPushServer.class);
    /**
     * 记录当前在线连接数
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();
    private static Map<String,String> sessionMap=new HashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "taskid") String taskid) {
        onlineCount.incrementAndGet(); // 在线数加1
        //String key=session.getId();
        String key=session.getId()+"_"+taskid;
        clients.put(key, session);
        sessionMap.put(session.getId(),key);
        LOG.info("有新连接加入，工作计划编号：{}，当前总连接数为：{}", taskid, onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet(); // 在线数减1
        clients.remove(sessionMap.get(session.getId()));
        sessionMap.remove(session.getId());
        LOG.info("有一连接关闭，工作计划编号：{}，当前总连接数为：{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        LOG.info("服务端收到客户端[{}]的消息[{}]", session.getId(), message);
    }

    /**
     * 给前端WEB界面推送违章消息消息
     * @param taskid 工作计划id
     * @param msg 消息内容
     */
    public static void push(String taskid, String msg) {
        LOG.debug("推送消息：" + msg);
        String str1="";
        String str2="";
        for(String key : clients.keySet()){
            try {
                int flag = key.indexOf("_");
                if (flag!=-1){
                    str1=key.substring(0, flag);
                    str2=key.substring(str1.length()+1, key.length());
                    if (str2.equals(taskid)){
                        clients.get(key).getBasicRemote().sendText(msg);
                    }
                }
            }catch (Exception e){
                LOG.info(e.getMessage());
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        LOG.error("发生错误");
    }
}
